<!--
 * @Author: LiYuan
 * @Date: 2021-02-02 16:18:41
 * @LastEditTime: 2024-04-22 16:47:03
 * @LastEditors: 铃兰 wanglili@publink.cn
 * @Description: 办理出入库-单个办理-申领or退回
 * @You build it, You run it.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :width="width"
    @open="partDearOpen"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <part-deal-with-form
      ref="partDealWithForm"
      :part-deal-key="partDealKey"
      @updateDetail="updateDetail"
      @updateList="updateList"
      :target-list="targetList"
      :prop-data="formdata"
      :approveData="approveData"
      @openApproveDialog="openApproveDialog"
      :approveId="approveId"
      :approveState="approveState"
    ></part-deal-with-form>

    <div
      slot="footer"
      class="dialog-footer flex-x"
      v-if="formdata.data.state === 'suspending' || formdata.data.state === 'dealing'"
    >
      <div class="ding-btn" v-if="isDingDingDesktop && formdata.data.cancel" @click="dingMessage">
        <i class="iconfont icon-Ding"></i>
        DING
      </div>

      <div class="flex-1"></div>
    
      <!-- 审批按钮 -->
      <template v-if="isShowApproveBtn">
        <div v-for="item in approveButtonData" :key="item.code">
          <el-button class="ml_12" :type="item.codeStr == 'refuse' ? 'danger' : 'primary'" @click="openApproveDialog(item.enName)">{{ item.cnName }}</el-button>
        </div>
      </template>
      <template v-if="approveState == 'success' || !approveId">
      <!-- 撤销 -->
      <el-button
        class="mar-r-15"
        type="ghost"
        v-if="formdata.data.cancel"
        @click="handleRevoke"
      >{{ this.$t('common.base.revoke')}} </el-button>

      <!-- 拒绝 -->
      <el-button
        class="mar-r-15"
        type="danger"
        v-if="formdata.data.isreject"
        @click="handleReject"
      >{{ this.$t('common.base.refuse')}}</el-button>

      <!-- 办理 -->
      <el-button
        type="primary"
        v-if="formdata.data.approved "
        @click="handleProcess"
        :disabled="pending"
        :loading="pending"
      >{{ this.$t('common.base.dealWith')}}</el-button>
    </template>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
import PartDealWithForm from '../form/PartDealWithForm.vue';
import { approveBatch } from '@src/api/SparePart';
import { getRootWindow } from '@src/util/dom';
import Platform from '@src/util/platform.ts';
import { getApproveLoad } from '@src/api/SparepartApprove.ts';

export default {
  name: 'single-handle-dialog',
  components: {
    PartDealWithForm
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '90%'
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    formdata: {
      type: Object,
      default: () => { }
    },
    targetList: {
      type: Array,
      default: () => []
    }
  },
  data: () => {
    return {
      visible: false,
      pending: false,
      partDealKey: 1,
      approveData: {},
      approveButtonData: [],
    }
  },
  computed: {
    isDingDingDesktop() {
      return Platform.isDingDingDesktop()
    },
    /**审批id */
    approveId() {
      return this.approveInfo?.id || '';
    },
    /**审批信息 */
    approveInfo() {
      return this.formdata.data?.approveInfo || {}
    },
    /**审批状态 */
    approveState() {
      return this.approveInfo?.state || '';
    },
    /** 当前登陆用户 */
    loginUser(){
      return window?.parent?.loginUser || {}
    },
    /** 是否显示审批操作按钮*/ 
    isShowApprove(){
      if(this.approveInfo?.approvers) {
        const approvers = JSON.parse(this.approveInfo.approvers) || [];
        return approvers.some(item=> item.userId == this.loginUser.userId )
      }else {
        return false
      }
    },
    /**是否显示审批按钮 */
    isShowApproveBtn() {
      return this.visible && this.approveId && this.approveButtonData.length && this.approveState !== 'success' && this.isShowApprove
    }
   
  },
  watch: {
    dialogVisible(val) {
      this.visible = val
      //备件高级审批处理 
      if(!this.visible) {
        this.approveData = {};
        this.approveButtonData = [];
      }
      if(this.approveId && this.visible) {
        this.getApproveDataReq();
      }
    }
  },
  methods: {
    /** 高级审批按钮操作 */
    async openApproveDialog(type) {
      let approveListRelations = []
      if(type !=='refuse') {
        const res = await this.handleApproveData(type);
        approveListRelations = res || [];
        if(approveListRelations.length == 0) return
      }
     
      this.$refs.partDealWithForm.openApproveDialog(type, approveListRelations, this.approveInfo)
    },
     /** 获取审批详情信息 */
    async getApproveDataReq() {
      try {
        const params = {
          approveId: this.approveId,
          taskId: this.formdata.data.businessInfoId,
        }
        const { code, result, message } = await getApproveLoad(params);

        if (code !== 0) return this.$message.warning(message)
        
        // 用于高级审批办理弹窗展示
        this.approveData = result;
        this.approveButtonData = result?.approveInfo?.buttons || [];
      } catch (err) {
        console.log('error => getApproveData', err);
      } 
    },

    // 打开详情弹窗
    partDearOpen(){
      this.$nextTick(() => {
        this.partDealKey++;
        if(this.$refs.partDealWithForm){
          this.$refs.partDealWithForm.suggestion = '';
        }
      })
    },

    updateList(){
      this.$emit('success')
    },

    dingMessage() {
      let rootWindow = getRootWindow(window);
      rootWindow.send_ding_part_message(
        this.formdata.data.staffs,
        this.formdata.data.approveNo
      );
    },

    updateDetail() {
      this.$emit('updateDetail')
    },

    handleClose() {
      this.$emit('close')
    },

    // 撤销
    handleRevoke() {
      this.$emit('handleRevoke')
    },

    // 拒绝
    handleReject() {
      this.$emit('handleReject')
    },
    /** 处理待办理的数据 */
    async handleApproveData(type) { 
      try { 
        const res = await this.$refs.partDealWithForm.getData(); 
        console.log(222, res)
        const { propData: { data, arr }, suggestion } = res;

        const filteredArr = (arr || []).filter(item => item.handleNum > 0).map(item => ({
            approveNo: data.approveNo,
            id: item.id,
            remark: suggestion,
            solvedVariation: item.handleNum,
            type: data.type
        }));

        if (filteredArr.length === 0 && type !=='refuse') {
            this.pending = false;
            this.$message({
                showClose: true,
                message: this.$t('sparepart.setting.setApprover.noApproverMsg'),
                type: 'warning'
            });
        }

        return filteredArr;
      } catch (error) {
          // 错误处理
          this.$message({
            showClose: true,
            message: error.message,
            type: 'error'
          });
          console.log(error)
      }
    },

    // 办理
    handleProcess: _.debounce(async function () {
      if (this.pending) return;

      this.pending = true;

      // 办理
      let data = this.$refs.partDealWithForm
        .getData()
        .then(res => {
          let arr = [];
          res.propData.arr.forEach(item => {
            if (item.handleNum > 0) {
              arr.push({
                approveNo: res.propData.data.approveNo,
                id: item.id,
                remark: res.suggestion,
                solvedVariation: item.handleNum,
                type: res.propData.data.type
              });
            }
          });

          if (arr.length <= 0) {
            this.pending = false;
            return this.$message({
              showClose: true,
              message: '没有可以办理的备件！',
              type: 'warning'
            });
          }
          approveBatch(arr)
            .then(res_ => {
              if (res_.code == 0) {
                this.$refs.partDealWithForm.resetData();
                this.$message({
                  showClose: true,
                  message: res_.message,
                  type: 'success'
                });
                this.$emit('success')
              } else {
                this.$message({
                  showClose: true,
                  message: res_.message || 'http error',
                  type: 'error'
                });
              }
            })
            .catch(err => {

            })
            .finally(() => {
                setTimeout(() => {
                  this.pending = false;
                }, 1000)
              
            });
        })
        .catch(err => {
          this.pending = false;
          this.$message({
            showClose: true,
            message: err.message,
            type: 'error'
          });
        });

    }, 1000),
  }
}
</script>

<style>
</style>